#!/usr/bin/env python3
"""
Fix remaining LaTeX syntax errors in the document.
"""

import re
from pathlib import Path
import glob

def fix_chapter_errors(content):
    """Fix malformed chapter commands."""
    # Fix chapter{include "[corrected_path]"} - this looks like a template artifact
    content = re.sub(r'\\chapter\{include\s*"?\[corrected_path\]"?\}', 
                     r'\\chapter{Corrected Implementation}', content)
    
    # Fix any other malformed chapter commands
    content = re.sub(r'\\chapter\{include\s*"[^"]*"\}', 
                     r'\\chapter{Implementation}', content)
    
    return content

def fix_texttt_errors(content):
    """Fix texttt command syntax errors."""
    # Fix common texttt issues - ensure proper braces
    # Fix cases where texttt is not properly closed
    content = re.sub(r'\\texttt\{([^}]*?)(\s+script\s+functionality)', 
                     r'\\texttt{\1} script functionality', content)
    
    # Fix texttt commands that might be missing closing braces
    content = re.sub(r'\\texttt\{([^{}]*?)\.py([^}]*?)(\s)', 
                     r'\\texttt{\1.py}\3', content)
    
    return content

def fix_math_mode_errors(content):
    """Fix math mode related errors."""
    # Fix underscore issues in text mode - should be \_
    content = re.sub(r'([^\\])_([a-zA-Z])', r'\1\_\2', content)
    
    # Fix cases where math symbols appear in text
    content = re.sub(r'([^$])\\alpha([^$])', r'\1$\\alpha$\2', content)
    content = re.sub(r'([^$])≈([^$])', r'\1$\\approx$\2', content)
    
    return content

def fix_special_characters(content):
    """Fix special characters that cause issues."""
    # Replace Unicode characters that might not be available
    replacements = {
        '❌': r'\\textcolor{red}{$\\times$}',
        '✅': r'\\textcolor{green}{$\\checkmark$}',
        'α': r'$\\alpha$',
        '≈': r'$\\approx$',
    }
    
    for unicode_char, latex_replacement in replacements.items():
        content = content.replace(unicode_char, latex_replacement)
    
    return content

def fix_listing_issues(content):
    """Fix remaining listing-related issues."""
    # Ensure proper lstlisting environments
    # Fix cases where listing content might have LaTeX commands
    lines = content.split('\n')
    in_listing = False
    result_lines = []
    
    for line in lines:
        if '\\begin{lstlisting}' in line:
            in_listing = True
            result_lines.append(line)
        elif '\\end{lstlisting}' in line:
            in_listing = False
            result_lines.append(line)
        elif in_listing:
            # In listing - escape problematic characters
            # Remove LaTeX commands that shouldn't be in listings
            if line.strip().startswith('\\chapter{') and 'Pattern' in line:
                # This looks like a comment about patterns, convert to comment
                line = '# ' + line.strip().replace('\\chapter{', '').replace('}', '')
            result_lines.append(line)
        else:
            result_lines.append(line)
    
    return '\n'.join(result_lines)

def fix_file(file_path):
    """Fix errors in a single LaTeX file."""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        original_content = content
        
        # Apply fixes in sequence
        content = fix_chapter_errors(content)
        content = fix_texttt_errors(content)
        content = fix_math_mode_errors(content)
        content = fix_special_characters(content)
        content = fix_listing_issues(content)
        
        # Write back if changed
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"Fixed syntax errors in {file_path}")
            return True
        else:
            print(f"No syntax errors found in {file_path}")
            return False
            
    except Exception as e:
        print(f"Error processing {file_path}: {e}")
        return False

def main():
    """Fix syntax errors in all LaTeX files."""
    files_to_check = ['claude-code-development-book.tex'] + glob.glob('chapters/*.tex')
    
    total_fixed = 0
    
    for file_path in files_to_check:
        if Path(file_path).exists():
            if fix_file(file_path):
                total_fixed += 1
    
    print(f"\n=== Summary ===")
    print(f"Fixed syntax errors in {total_fixed} files")
    
    if total_fixed > 0:
        print("\nRecommendation: Re-run xelatex to verify fixes")

if __name__ == "__main__":
    main()